var wechat = require('wechat'),
express = require('express'),
request = require('request'),
log = require('../lib/log'),
citys = require('../lib/cityparser');

var APPKEY = 'eceecf7a96d8c4d6beda7482d3408e70';
var APPURI = ' http://www.tuling123.com/openapi/api';

var helpInfo = 	
'回复【菜单】进入点餐界面\n' +
'你可以模仿如下句子和西大小兔聊天：\n' +
'重庆天气\n' +
'天秤座今日运势\n' +
'翻译国家\n' +
'讲个故事\n' +
'讲个笑话\n' +
'背一首诗\n' +
'小苹果歌词\n' +
'解梦：梦到桃花怎么回事\n' +
'你也可以回复【任意内容】，小兔兔会陪你聊天的\n' +
'回复【帮助】可以看到如上内容';

var menuRegExp = /(菜单|点餐|夜点|宵夜|宵夜|订餐|美食|饿)/m;

module.exports = function(app) {
	app.use(express.query());
	app.use('/wechat', wechat('fourblock', function (req, res, next) {
		var message = req.weixin;
		if (message.MsgType === 'event' && message.Event === 'subscribe') {
			res.reply({
				type: 'text',
				content: helpInfo
			});
		} else if (message.MsgType === 'text' && message.Content === '帮助') {
			res.reply({
				type: 'text',
				content: helpInfo
			});
		} else if (message.MsgType === 'text' && menuRegExp.test(message.Content)) {
			res.reply([
			{
				title: '西大小兔为你准备了丰富的美食',
				description: '点击图片进入菜单页面',
				picurl: 'http://xdzs.sturgeon.mopaas.com/static/image/food.png',
				url: 'http://xdzs.sturgeon.mopaas.com/shop/list?uid=' + message.FromUserName
			}
			]);
		} else if (message.MsgType === 'text') {
			var requestURL = APPURI + '?key=' + APPKEY + '&info=' + message.Content + '&userid=' + message.FromUserName;
			request(requestURL, function(err, response, body) {
				if (err) {
					log.error(err);
					res.reply({type: 'text', content: '靠！调戏我的小伙伴太多了无法及时回复你请重试。'});
					return;
				}
				try {
					var result = JSON.parse(body);
					res.reply({type: 'text', content: result.text});
				} catch (e) {
					res.reply({type: 'text', content: body});
				}
			});
		} else {
			res.reply({type: 'text', content: '小兔兔只能理解文本消息哦亲。'});
		}
	}));
};
